const express = require('express');
const app = express();
// 校验token模块
const expjwt = require('express-jwt');
const login = require('./router/login');
const register = require('./router/register');
const collect = require('./router/collect');
const gedan = require('./router/gedan');
const comment = require('./router/comment');
const music = require('./router/music');
const mv = require('./router/mv');
const singer = require('./router/singer');
const news = require('./router/news');
const info = require('./router/info');
const datas = require('./router/data');
const search = require('./router/search');
const {
	sendError
} = require('./utils/sendFunction');

// 跨域设置
app.use((req, res, next) => {
	res.setHeader('Access-Control-Allow-Origin', '*');
	res.setHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
	res.setHeader('Access-Control-Allow-Credentials', true);
	res.setHeader('Access-Control-Allow-Headers', '*');
	next();
})

// 获取参数
app.use(express.json());
app.use(express.urlencoded({
	extended: false
}));

// 静态资源设置
app.use('/uploads', express.static('uploads'))

// 校验token
var str = 'secret';
app.use(expjwt({
	secret: str,
	algorithms: ["HS256"]
}).unless({
	path: [/^\/uploads\//, /^\/login\//, /^\/register\//, /^\/data\//]
}));


// 登录
app.use('/login', login);
// 注册
app.use('/register', register);
// 收藏
app.use('/collect', collect);
// 歌单
app.use('/gedan', gedan);
// 评论
app.use('/comment', comment);
// 音乐
app.use('/music', music);
// mv
app.use('/mv', mv);
// 歌手
app.use('/singer', singer);
// 新闻
app.use('/news', news);
// 用户管理员信息
app.use('/info', info);
// 数据
app.use('/data', datas);
// 搜索
app.use('/search',search);

// 阻止 防止响应404
app.get('/undefined', (req, res) => {
	res.send('ok');
})

// 错误处理
app.use(function (err, req, res, next) {
	if (err.message === 'No authorization token was found' || err.message == 'invalid token' || err.message == 'jwt expired') {
		sendError(res, 200, '解析token字符串失败或token字符串不正确或token字符串过期');
	} else {
		sendError(res, 200, err.message);
	}
})


app.listen(3001);
console.log('localhost:3001');